package com.example.demo.msg.netty.server;

import com.example.demo.msg.netty.common.IMconfig;
import com.example.demo.msg.netty.common.Imessage;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

public class ServerHandler extends ChannelInboundHandlerAdapter implements IMconfig {

    public static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    public boolean sendMsg(Imessage msg,Channel curChannel){
        System.err.println("服务器推送消息:"+msg);

        if("q".equals(msg.getMsg())) return false;

        for(Channel channel:channels){

            if(channel != curChannel) {
              msg.setMsg("[you]:"+msg.getMsg());
            }

            channel.writeAndFlush(msg);

        }

        return false;

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.err.println("客户端西掉线："+ctx.channel().remoteAddress().toString());
        super.channelInactive(ctx);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        System.err.println("有客户端连接："+ctx.channel().remoteAddress().toString());

    }



    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.err.println("服务器接收到消息:"+msg);
        Imessage message = (Imessage)msg;

        sendMsg(message,ctx.channel());

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.err.println("与客户端断开连接:"+cause.getMessage());
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.err.println("服务端Handler创建...");
        super.handlerAdded(ctx);

        channels.add(ctx.channel());

    }
}